package org.example.SolutionNew002;

public class LinkedList09 {
    public static void main(String[] args) {
        LinkedList09 l = new LinkedList09();
        ListNode head1 = new ListNode(1);
        head1.next = new ListNode(2);
        head1.next.next = new ListNode(3);
        head1.next.next.next = new ListNode(4);
        head1.next.next.next.next = new ListNode(5);
        ListNode res=l.swapPairs(head1);
        while(res!=null){
            System.out.println(res.val);
            res=res.next;
        }
    }

    public ListNode swapPairs1(ListNode head) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode prNode = dummy;
        if(dummy.next == null||dummy.next.next==null) return head;
        int curr=1;
        ListNode prev = dummy.next;
        while(prev!=null){
            if(curr%2==0){
                ListNode temp=prNode.next;
                prNode.next=temp.next;
                temp.next=prev.next;
                prev.next=temp;
                prev=temp;
                prNode=temp;
            }
            curr++;
            prev=prev.next;
        }
        return dummy.next;
    }

    //递归
    public ListNode swapPairs2(ListNode head) {
        if(head==null||head.next==null) return head;

        ListNode newHead = head.next;
        head.next = swapPairs2(newHead.next);
        newHead.next = head;
        return newHead;
    }

    //我的方案1的改良版，迭代
    public ListNode swapPairs(ListNode head) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode prev = dummy;
        while(prev.next!=null&&prev.next.next!=null){
            ListNode temp1=prev.next;
            ListNode temp2=prev.next.next;
            temp1.next = temp2.next;
            prev.next=temp2;
            temp2.next=temp1;
            prev=temp1;
        }
        return dummy.next;
    }
}
